package com.beiing.tianshuai.tianshuai.dongtai.view;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Rect;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.beiing.tianshuai.tianshuai.R;
import com.beiing.tianshuai.tianshuai.activity.MainActivity;
import com.beiing.tianshuai.tianshuai.base.BaseActivity;
import com.beiing.tianshuai.tianshuai.dongtai.presenter.DynamicPublishPresenter;
import com.beiing.tianshuai.tianshuai.entity.DynamicImageInfo;
import com.beiing.tianshuai.tianshuai.entity.DynamicPublishBean;
import com.beiing.tianshuai.tianshuai.entity.DynamicPublishImageBean;
import com.beiing.tianshuai.tianshuai.fragment.EmotionCompleteFragment;
import com.beiing.tianshuai.tianshuai.itemtouch.DefaultItemTouchHelper;
import com.beiing.tianshuai.tianshuai.itemtouch.DefaultItemTouchHelperCallback;
import com.beiing.tianshuai.tianshuai.util.GlobalOnItemClickManagerUtils;
import com.beiing.tianshuai.tianshuai.util.ImgUtils;
import com.beiing.tianshuai.tianshuai.util.LogUtils;
import com.beiing.tianshuai.tianshuai.util.SPUtils;
import com.beiing.tianshuai.tianshuai.widget.CustomProgressDialog;
import com.beiing.tianshuai.tianshuai.widget.GlideImageLoader;
import com.netease.nim.uikit.common.util.log.LogUtil;
import com.tianshuai.gallerypic.config.GalleryConfig;
import com.tianshuai.gallerypic.config.GalleryPick;
import com.tianshuai.gallerypic.inter.IHandlerCallBack;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;

import butterknife.BindView;
import cn.jpush.android.api.JPushInterface;

/**
 * 动态发布界面
 *
 * @author Administrator
 * @date 2017/7/25
 */

public class DynamicPublishActivity extends BaseActivity implements View.OnClickListener,
        DynamicPublishActivityViewImpl {

    @BindView(R.id.toolbar_iv_back)
    ImageView titleBack;
    @BindView(R.id.toolbar_tv_title)
    TextView titleText;
    @BindView(R.id.toolbar_center_title)
    TextView centerTitle;
    @BindView(R.id.toolbar_iv_publish)
    ImageView ivTitlePublish;
    /**
     * 发送按钮
     */
    @BindView(R.id.toolbar_btn_publish)
    TextView btnTitlePublish;
    @BindView(R.id.toolbar)
    Toolbar toolbar;
    /**
     * 输入想要说的话
     */
    @BindView(R.id.edit_dynamic_publish)
    EditText dynamicContent;
    @BindView(R.id.text_num)
    TextView textNum;
    @BindView(R.id.rv_images_list)
    RecyclerView mList;
    @BindView(R.id.ll_emoji_input)
    LinearLayout llEmojiInput;
    @BindView(R.id.iv_face)
    ImageView ivFace;
    @BindView(R.id.iv_keyboard)
    ImageView ivKeyBoard;
    @BindView(R.id.fl_emotionview_main)
    FrameLayout mEmotionLayout;


    private static final int PERMISSIONS_REQUEST_READ_CONTACTS = 100;
    private static final String TAG = "DynamicPublishActivity";

    /**
     * 用户Id
     */
    private String mUserId;

    /**
     * 极光推送SDK向JPush Server注册所得到的注册ID
     */
    private String mRegistrationId;

    private DynamicPublishImageAdapter mAdapter;
    private InputMethodManager imm;

    private List<String> fileOutputPaths = new ArrayList<>();

    /**
     * 主持人
     */
    private DynamicPublishPresenter mPresenter;

    private Handler mHandler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            int what = msg.what;
            switch (what) {
                case 0:
                    String content = dynamicContent.getText().toString().trim();
                    try {
                        String contentUTF8 = URLEncoder.encode(content, "UTF-8");
                        //子线程执行完才进行发布动态操作
                        dynamicPublish(mUserId, contentUTF8, mRegistrationId);
                    } catch (UnsupportedEncodingException e) {
                        e.printStackTrace();
                    }
                    break;
                default:
                    break;
            }
            return false;
        }
    });

    /**
     * RecyclerView Item的触摸事件监听
     */
    private DefaultItemTouchHelperCallback.OnItemTouchCallbackListener mOnItemTouchCallbackListener = new DefaultItemTouchHelperCallback.OnItemTouchCallbackListener() {
        @Override
        public void onSwiped(int adapterPosition) {
            if (mAdapter != null) {
                mAdapter.removeData(adapterPosition);
            }
        }

        @Override
        public boolean onMove(int srcPosition, int targetPosition) {
            if (mAdapter != null) {
                // 更新UI中item的位置
                mAdapter.swapMoved(srcPosition, targetPosition);
            }
            return false;
        }
    };
    private ExecutorService mCachedThreadPool;

    public static void star(Context context) {
        Intent intent = new Intent(context, DynamicPublishActivity.class);
        context.startActivity(intent);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_dynamic_publish;
    }

    @Override
    protected void init() {
        //创建线程池，进行压缩耗时操作
        mCachedThreadPool = Executors.newCachedThreadPool();
        initToolbar();
        initRecyclerView();
        initPresenter();
        initListener();
        mUserId = SPUtils.getString(this, "uid", null);
        mRegistrationId = JPushInterface.EXTRA_REGISTRATION_ID;
        imm = (InputMethodManager) mContext.getSystemService(Context.INPUT_METHOD_SERVICE);
        initEmotionMainFragment();
        llEmojiInput.setVisibility(View.VISIBLE);
    }

    public void initPresenter() {
        mPresenter = new DynamicPublishPresenter(this);
    }

    private void initEmotionMainFragment() {
        GlobalOnItemClickManagerUtils globalOnItemClickManager = GlobalOnItemClickManagerUtils.getInstance(mContext);
        globalOnItemClickManager.attachToEditText(dynamicContent);
        EmotionCompleteFragment emotionCompleteFragment = new EmotionCompleteFragment();
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        transaction.add(R.id.fl_emotionview_main, emotionCompleteFragment);
        transaction.commit();
    }

    private void initToolbar() {
        titleText.setVisibility(View.GONE);
        centerTitle.setVisibility(View.VISIBLE);
        centerTitle.setText("编辑内容");
        ivTitlePublish.setVisibility(View.GONE);
        btnTitlePublish.setVisibility(View.VISIBLE);
        btnTitlePublish.setBackgroundResource(R.drawable.publish_gray);
        titleBack.setVisibility(View.VISIBLE);
    }

    private void initRecyclerView() {
        mAdapter = new DynamicPublishImageAdapter(mContext);
        mList.setAdapter(mAdapter);
        GridLayoutManager gridLayoutManager = new GridLayoutManager(mContext, 4);
        /*
         *  设置SpanSizeLookup，它将决定view会横跨多少列。这个方法是为RecyclerView添加Header和Footer的关键。
         *  当判断position指向的View为Header或者Footer时候，返回总列数 lm.getSpanCount() ,即可让其独占一行。
         */
        mList.setNestedScrollingEnabled(false);
        mList.setLayoutManager(gridLayoutManager);
        //绘制item间的分割线，
        mList.addItemDecoration(new RecyclerView.ItemDecoration() {
            @Override
            public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
                outRect.set(10, 10, 10, 10);
            }
        });
        mList.setItemAnimator(new DefaultItemAnimator());

        // 设置ItemTouchListener
        DefaultItemTouchHelper defaultItemTouchHelper = new DefaultItemTouchHelper(mOnItemTouchCallbackListener);
        defaultItemTouchHelper.attachToRecyclerView(mList);
        defaultItemTouchHelper.setDragEnable(true);
        defaultItemTouchHelper.setSwipeEnable(false);
    }

    private void initListener() {
        // 图片点击事件
        mAdapter.setOnItemClickListener(new DynamicPublishImageAdapter.OnItemClickListener() {
            @Override
            public void onImageClickListener(View view, int position) {
                int size = mAdapter.getList().size();
                if (size < 9 && position == size) {
                    checkSelfPermission();
                } else {
                    updateImage(position);
                }
            }

            @Override
            public void onImageDeleteClickListener(View view, int position) {
                mAdapter.removeData(position);
                int size = mAdapter.getList().size();
                LogUtils.i(mAdapter.getList().toString(), TAG);
                if (size == 0 && TextUtils.isEmpty(dynamicContent.getText())) {
                    //如果没有输入发送按钮就变灰色
                    btnTitlePublish.setBackgroundResource(R.drawable.publish_gray);
                }
            }
        });

        titleBack.setOnClickListener(this);

        // 发送
        btnTitlePublish.setOnClickListener(this);

        // 内容
        dynamicContent.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                textNum.setText(MessageFormat.format("{0}/300", editable.length()));
                if (editable.length() > 0) {
                    btnTitlePublish.setBackgroundResource(R.drawable.publish_blue);
                } else {
                    btnTitlePublish.setBackgroundResource(R.drawable.publish_gray);
                }
            }
        });

        dynamicContent.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                llEmojiInput.setVisibility(View.VISIBLE);
                ivFace.setVisibility(View.VISIBLE);
                ivKeyBoard.setVisibility(View.GONE);
                mEmotionLayout.setVisibility(View.GONE);
            }
        });

        ivFace.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                ivFace.setVisibility(View.GONE);
                ivKeyBoard.setVisibility(View.VISIBLE);
                imm.hideSoftInputFromWindow(getWindow().getDecorView().getWindowToken(), 0);
                mEmotionLayout.setVisibility(View.VISIBLE);
            }
        });

        ivKeyBoard.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mEmotionLayout.setVisibility(View.GONE);
                ivKeyBoard.setVisibility(View.GONE);
                ivFace.setVisibility(View.VISIBLE);
                imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
                dynamicContent.setFocusable(true);
                dynamicContent.setFocusableInTouchMode(true);
                dynamicContent.requestFocus();
            }
        });
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.toolbar_iv_back:
                finish();
                break;
            case R.id.toolbar_btn_publish:
                if (TextUtils.isEmpty(dynamicContent.getText().toString().trim()) && mAdapter.getList().size() == 0) {
                    showShortText("请添加想发布的内容哦");
                    return;
                }
                showShortText("正在提交，请稍后...");
                view.setClickable(false);
                //发布
                CustomProgressDialog.showLoading(mContext, "正在提交数据...", false);
                //压缩开始
                compressImages();
                break;
            default:
                break;
        }
    }

    /**
     * 动态权限申请
     */
    private void checkSelfPermission() {
        if (ContextCompat.checkSelfPermission(mContext, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            LogUtils.i("需要授权", TAG);
            if (ActivityCompat.shouldShowRequestPermissionRationale(DynamicPublishActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
                LogUtils.i("拒绝过了", TAG);
                // 提示用户如果想要正常使用，要手动去设置中授权。
                showShortText("请在 设置-应用管理 中开启此应用的储存授权。");
            } else {
                LogUtils.i("进行授权", TAG);
                ActivityCompat.requestPermissions(DynamicPublishActivity.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, PERMISSIONS_REQUEST_READ_CONTACTS);
            }
        } else {
            LogUtils.i("不需要授权", TAG);
            // 进行正常操作
            selectImage();
        }
    }

    /**
     * 图片替换部分
     */
    private void updateImage(final int index) {
        List<String> path = new ArrayList<>();
        IHandlerCallBack iHandlerCallBack = new IHandlerCallBack() {
            @Override
            public void onStart() {
                LogUtils.i("----------------- 选图开始 -----------------", TAG);
            }

            @Override
            public void onSuccess(List<String> photoList) {
                String filesPath = photoList.get(0);
                //替换图片不压缩，每次只提换一张图片
                mAdapter.updateData(filesPath, index);
            }

            @Override
            public void onCancel() {
                LogUtils.i("用户已取消", TAG);
            }

            @Override
            public void onFinish() {
                LogUtils.i("----------------- 选图结束 -----------------", TAG);
            }

            @Override
            public void onError() {
                LogUtils.e("----------------- 选图异常 -----------------", TAG);
            }
        };
        GalleryConfig galleryConfig = new GalleryConfig.Builder()
                .imageLoader(new GlideImageLoader())
                .iHandlerCallBack(iHandlerCallBack)
                .provider("com.beiing.tianshuai.fileprovider")
                .pathList(path)
                .multiSelect(false)
                .crop(false)
                .isShowCamera(true)
                .filePath("/TianShuai/Pictures")
                .build();
        GalleryPick.getInstance().setGalleryConfig(galleryConfig).open(DynamicPublishActivity.this);
    }

    /**
     * 图片选择部分
     */
    private void selectImage() {
        int maxImgNum = 9 - mAdapter.getList().size();
        final List<String> path = new ArrayList<>();

        IHandlerCallBack iHandlerCallBack = new IHandlerCallBack() {
            @Override
            public void onStart() {
                LogUtils.i("----------------- 选图开始 -----------------", TAG);
            }

            @Override
            public void onSuccess(List<String> photoList) {

                btnTitlePublish.setBackgroundResource(R.drawable.publish_blue);
                final String[] filesPath = photoList.toArray(new String[photoList.size()]);
                for (String aFilesPath : filesPath) {
                    int size = mAdapter.getList().size();
                    if (size < 8) {
                        mAdapter.addData(size, aFilesPath);
                    } else {
                        mAdapter.appendData(aFilesPath);
                    }
                }
            }

            @Override
            public void onCancel() {
                LogUtils.i("用户已取消", TAG);
            }

            @Override
            public void onFinish() {
                LogUtils.i("----------------- 选图结束 -----------------", TAG);
            }

            @Override
            public void onError() {
                LogUtils.e("----------------- 选图异常 -----------------", TAG);
            }
        };

        GalleryConfig galleryConfig = new GalleryConfig.Builder()
                .imageLoader(new GlideImageLoader())
                .iHandlerCallBack(iHandlerCallBack)
                .provider("com.beiing.tianshuai.fileprovider")
                .pathList(path)
                .multiSelect(true, maxImgNum)
                .crop(false)
                .isShowCamera(true)
                .filePath("/TianShuai/Pictures")
                .build();
        GalleryPick.getInstance().setGalleryConfig(galleryConfig).open(DynamicPublishActivity.this);
    }

    /**
     * 发布文字活动内容  网络请求操作
     *
     * @param uid            用户id
     * @param content        内容
     * @param registrationId JPush注册id
     */
    private void dynamicPublish(String uid, String content, String registrationId) {
        CustomProgressDialog.showLoading(mContext, "正在提交数据...", false);
        String type = "1";
        LogUtil.i(TAG, "发布动态" + uid + content + registrationId + type);
        mPresenter.postDynamicPublishText(uid, content, registrationId, type);
    }

    /**
     * 发布活动的图片
     */
    private void dynamicPublishPic(String dynamicId) {
        CustomProgressDialog.showLoading(mContext, "正在上传图片...", false);
        LogUtil.i(TAG, "动态ID" + dynamicId + "图片数量" + fileOutputPaths.size());
        mPresenter.postDynamicPublishImage(dynamicId, fileOutputPaths);
    }

    /**
     * 图片压缩方法
     */
    private void compressImages() {
        final ArrayList<DynamicImageInfo> dynamicImageInfos = new ArrayList<>();
        List<String> list = mAdapter.getList();
        for (int i = 0; i < list.size(); i++) {
            String aFilesPath = list.get(i);
            //位图对象
            BitmapFactory.Options options = new BitmapFactory.Options();
            //禁止为bitmap分配内存，返回值也不再是一个Bitmap对象，而是null
            options.inJustDecodeBounds = true;
            //返回空，可以获得宽高
            Bitmap bitmap1 = BitmapFactory.decodeFile(aFilesPath, options);


            int imageHeight = options.outHeight;
            int imageWidth = options.outWidth;

            int ratio = imageHeight / imageWidth;
            LogUtil.i(TAG, "============" + imageHeight + " " + imageWidth);
            String fileType = ImgUtils.getFileType(aFilesPath);

            DynamicImageInfo dynamicImageInfo = new DynamicImageInfo();

            //如果是gif就不压缩
            if ("gif".equals(fileType)) {
                dynamicImageInfo.setType("gif");
            } else {
                //如果是长图且宽度小于1280就只进行质量压缩
                boolean isLongImage = imageHeight > 4096 && ratio > 2;

                if (isLongImage && imageWidth < 1280) {
                    dynamicImageInfo.setType("长图");
                } else {
                    dynamicImageInfo.setType("普通图");
                }
            }

            dynamicImageInfo.setPath(aFilesPath);
            dynamicImageInfo.setIndex(i);
            dynamicImageInfos.add(dynamicImageInfo);
        }

        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                for (int i = 0; i < dynamicImageInfos.size(); i++) {
                    DynamicImageInfo dynamicImageInfo = dynamicImageInfos.get(i);
                    String type = dynamicImageInfo.getType();
                    String path = dynamicImageInfo.getPath();
                    switch (type) {
                        case "gif":
                        case "长图":
                            fileOutputPaths.add(path);
                            break;
                        case "普通图":
                            BitmapFactory.Options optionsLong = new BitmapFactory.Options();
                            Bitmap bmp = BitmapFactory.decodeFile(path, optionsLong);
                            String outputPath = compressImg(bmp, type);
                            if (!TextUtils.isEmpty(outputPath)) {
                                fileOutputPaths.add(outputPath);
                            }
                            break;
                        default:
                            break;
                    }
                }
                Message message = new Message();
                message.what = 0;
                mHandler.sendMessage(message);
            }
        };
        //在线程池中开启线程
        mCachedThreadPool.execute(runnable);
    }

    @Override
    public void onBackPressed() {
        if (mEmotionLayout.getVisibility() == View.VISIBLE) {
            mEmotionLayout.setVisibility(View.GONE);
        } else {
            super.onBackPressed();
        }
    }

    private String compressImg(Bitmap bitmap, String type) {
        int options = 80;
        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.JPEG, options, stream);

        int maxLength;
        switch (type) {
            case "长图":
                maxLength = 800;
                break;
            case "普通图":
                maxLength = 600;
                break;
            default:
                maxLength = 800;
                break;
        }

        while (stream.toByteArray().length / 1024 > maxLength) {
            //重置到0
            stream.reset();
            options -= 10;
            if (options <= 0) {
                options = 10;
                //最高压缩度为10，不能再压缩了
                bitmap.compress(Bitmap.CompressFormat.JPEG, options, stream);
                break;
            }
            bitmap.compress(Bitmap.CompressFormat.JPEG, options, stream);
            LogUtil.i(TAG, "循环压缩" + options + " " + stream.size());
        }

        bitmap.recycle();

        String filePath = Environment.getExternalStorageDirectory() +
                "/TianShuai/天率校园/CompressPath/";
        File file = new File(filePath);
        if (!file.exists()) {
            if (file.mkdirs()) {
                LogUtils.i("路径创建成功", TAG);
            } else {
                LogUtils.i("路径创建失败", TAG);
            }
        }

        filePath += "img" + System.currentTimeMillis() + ".jpeg";
        file = new File(filePath);
        try {
            FileOutputStream fos = new FileOutputStream(file);
            fos.write(stream.toByteArray());
            //刷新写入
            fos.flush();
            fos.close();
            return filePath;
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //关闭线程池
        mCachedThreadPool.shutdown();
    }

    @Override
    public void postDynamicPublishTextSuccess(DynamicPublishBean dynamicPublishBean) {
        int code = dynamicPublishBean.getCode();
        switch (code) {
            case 200:
                LogUtil.i(TAG, "发布动态成功");
                //发布活动的Id
                String dynamicId = dynamicPublishBean.getData().getId();
                //开始发布图片
                dynamicPublishPic(dynamicId);
                break;
            case 404:
                showShortText("发布失败");
                LogUtil.i(TAG, "发布失败");
                break;
            case 405:
                showShortText("参数有误");
                LogUtil.i(TAG, "参数有误");
                break;
            default:
                break;
        }
    }

    @Override
    public void postDynamicPublishTextError(Throwable throwable) {
        showShortText("发布动态失败" + throwable.getMessage());
        LogUtil.i(TAG, "发布动态失败" + throwable.getMessage());
    }

    @Override
    public void postDynamicPublishImageSuccess(DynamicPublishImageBean dynamicPublishImageBean) {
        int code = dynamicPublishImageBean.getCode();
        switch (code) {
            case 200:
                LogUtil.i(TAG, "发布动态图片成功");
                MainActivity.isPublished = true;
                CustomProgressDialog.stopLoading();
                finish();
                break;
            case 404:
                btnTitlePublish.setClickable(true);
                LogUtil.i(TAG, "添加失败");
                CustomProgressDialog.stopLoading();
                break;
            case 405:
                btnTitlePublish.setClickable(true);
                LogUtil.i(TAG, "参数有误");
                break;
            default:
                btnTitlePublish.setClickable(true);
                break;
        }
    }

    @Override
    public void postDynamicPublishImageError(Throwable throwable) {
        btnTitlePublish.setClickable(true);
        showShortText("发布动态图片失败" + throwable.getMessage());
        LogUtil.i(TAG, "发布动态图片失败" + throwable.getMessage());
    }

    @Override
    public void showProgress() {

    }

    @Override
    public void hideProgress() {

    }

    @Override
    public void onRequestSuccess(DynamicPublishBean bean) {

    }

    @Override
    public void onRequestFailed(Throwable throwable) {

    }
}